﻿using System;
using System.Diagnostics;
using System.IO;
using Microsoft.SharePoint;

namespace zevenseas.Community.CKS.Search.Features
{
    class BlogSearchProvisioning : SPFeatureReceiver
    {
        SPWeb currentWeb = null;
        SPSite currentSite = null;

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            object oParent = properties.Feature.Parent;

            if (oParent is SPWeb)
            {
                currentWeb = (SPWeb)oParent;
                currentSite = currentWeb.Site;
            }
            else
            {
                currentSite = (SPSite)oParent;
                currentWeb = currentSite.RootWeb;
            }

            SPFolder oRootFolder = currentWeb.RootFolder;
            AddSearchPage(oRootFolder, "Search.aspx", properties.Definition.RootDirectory);
        }

        protected static void AddSearchPage(SPFolder destFolder, string fileName, string featureFolder)
        {
            Stream fileStream = null;

            try
            {
                fileStream = File.Open(featureFolder + "\\Pages\\" + fileName, FileMode.Open);
                destFolder.Files.Add(fileName, fileStream);
                fileStream.Close();
            }
            catch (Exception ex)
            {
                Debug.Write("Adding as Application Pool..." + fileName);
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    fileStream = File.Open(featureFolder + "\\Pages\\" + fileName, FileMode.Open);
                    destFolder.Files.Add(fileName, fileStream);
                    fileStream.Close();
                });
            }
            finally
            {
                if (fileStream != null) fileStream.Dispose();
            }
        }
     
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            //throw new Exception("The method or operation is not implemented.");
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            //throw new Exception("The method or operation is not implemented.");
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            //throw new Exception("The method or operation is not implemented.");
        }
    }
}